package cn.wolfcode.luowowo.website.web.controller;

import cn.wolfcode.luowowo.article.domain.*;
import cn.wolfcode.luowowo.article.query.TravelQuery;
import cn.wolfcode.luowowo.article.service.IDestinationService;
import cn.wolfcode.luowowo.article.service.IStrategyDetailService;
import cn.wolfcode.luowowo.article.service.ITravelService;
import cn.wolfcode.luowowo.cache.service.ITravelStatisVOService;
import cn.wolfcode.luowowo.comment.domain.TravelComment;
import cn.wolfcode.luowowo.comment.query.TravelCommentQuery;
import cn.wolfcode.luowowo.comment.service.ITravelCommentService;
import cn.wolfcode.luowowo.common.util.AjaxResult;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.website.web.annotation.RequireLogin;
import cn.wolfcode.luowowo.website.web.annotation.UserParam;
import cn.wolfcode.luowowo.website.web.util.UMEditorUploader;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
@RequestMapping("/travel")
public class TravelController {

    @Value("${file.path}")
    private String filePath;

    @Reference
    private ITravelService travelService;
    @Reference
    private IDestinationService destinationService;
    @Reference
    private IStrategyDetailService detailService;
    @Reference
    private ITravelCommentService travelCommentService;
    @Reference
    private ITravelStatisVOService travelStatisVOService;


    @RequestMapping("")
    public String list(Model model, @ModelAttribute("qo") TravelQuery qo){

        //pageInfo  全部游记
        model.addAttribute("pageInfo",travelService.query(qo));

        return "travel/list";
    }


    @RequestMapping("/detail")
    public String detail(Model model,Long id,@UserParam UserInfo userInfo){

        //detail    明细
        Travel travel = travelService.get(id);
        TravelContent content = travelService.getContent(id);
        travel.setTravelContent(content);
        model.addAttribute("detail",travel);

        //ret  编辑按钮的显示
        boolean ret = userInfo!= null ? userInfo.getId() == travel.getAuthor().getId() : false;
        model.addAttribute("ret",ret);

        Long destId = travel.getDest().getId();
        //toasts   吐丝
        List<Destination> toasts = destinationService.getToasts(destId);
        model.addAttribute("toasts", toasts);

        //sds   根据当前篇游记的目的地查询该目的地下阅读量为前3的攻略
        List<StrategyDetail> sds = detailService.listViewnumTop3(destId);
        model.addAttribute("sds",sds);

        //ts    根据当前篇游记的目的地查询该目的地下阅读量为前3的游记
        List<Travel> list = travelService.listViewnumTop3(destId);
        model.addAttribute("ts",list);

        //list  所有评论
        TravelCommentQuery qo = new TravelCommentQuery();
        qo.setTravelId(id);
        qo.setCurrentPage(1);
        qo.setPageSize(Integer.MAX_VALUE);
        Page page = travelCommentService.query(qo);
        model.addAttribute("list",page.getContent());
        //travelCommentService.listByTravelId(id);

        //游记阅读数 +1
        travelStatisVOService.incrViewnum(id,1);
        model.addAttribute("vo",travelStatisVOService.getStatisVO(id));

        return "travel/detail";
    }


    @RequireLogin
    @RequestMapping("/input")
    public String input(Model model, Long id){

        //dests 目的地
        model.addAttribute("dests",destinationService.getDestsByDeep(3));
        //tv    内容回显
        if (id != null){
            Travel travel = travelService.get(id);
            TravelContent content = travelService.getContent(id);
            travel.setTravelContent(content);
            model.addAttribute("tv",travel);
        }
        return "travel/input";
    }


    @RequireLogin
    @RequestMapping("/saveOrUpdate")
    @ResponseBody
    public Object saveOrUpdate(@UserParam UserInfo userInfo, Travel travel){
        travel.setAuthor(userInfo);
        AjaxResult ajaxResult = travelService.saveOrUpdate(travel);
        return ajaxResult;
    }


    @RequestMapping("/commentAdd")
    public String commentAdd(Model model, int floor, TravelComment comment,@UserParam UserInfo userInfo){

        comment.setCity(userInfo.getCity());
        comment.setUsername(userInfo.getNickname());
        comment.setHeadUrl(userInfo.getHeadImgUrl());
        comment.setUserId(userInfo.getId());
        comment.setLevel(userInfo.getLevel());
        TravelComment travelComment = travelCommentService.save(comment);//需要把保存之后的对象返回共享给页面
        //c
        model.addAttribute("c",travelComment);
        //floor
        model.addAttribute("floor",travelCommentService.getCount(comment.getTravelId()));
        return "travel/commentTpl";
    }

    //游记收藏
    @RequestMapping("/favor")
    @ResponseBody
    public Object favor(Long tid,@UserParam UserInfo userInfo){
        AjaxResult result = new AjaxResult();
        if (userInfo == null){
            //没有登录
            result.setCode(AjaxResult.NO_LOGIN_CODE);
            result.mark("请先登录");
            return result;
        }
        //true表示收藏操作
        boolean ret = travelStatisVOService.favor(tid, userInfo.getId());

        //查询当前收藏数
        return  ret ? result.addData(travelStatisVOService.getStatisVO(tid)) : result.addData1(travelStatisVOService.getStatisVO(tid));
    }



    //上传图片
    @RequestMapping("/contentImage")
    @ResponseBody
    public String uploadUEImage(MultipartFile upfile, HttpServletRequest request) throws Exception{
        UMEditorUploader up = new UMEditorUploader(request);
        String[] fileType = {".gif" , ".png" , ".jpg" , ".jpeg" , ".bmp"};
        up.setAllowFiles(fileType);
        up.setMaxSize(10000); //单位KB
        up.upload(upfile, filePath);

        String callback = request.getParameter("callback");
        String result = "{\"name\":\""+ up.getFileName() +"\", \"originalName\": \""+ up.getOriginalName() +"\", \"size\": "+ up.getSize()
                +", \"state\": \""+ up.getState() +"\", \"type\": \""+ up.getType() +"\", \"url\": \""+ up.getUrl() +"\"}";
        result = result.replaceAll( "\\\\", "\\\\" );
        if(callback == null ){
            return result ;
        }else{
            return "<script>"+ callback +"(" + result + ")</script>";
        }
    }

}
